package com.ai.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ai.web.http.HttpResponse;
import com.ai.web.http.HttpUtil;
import com.ai.web.service.WxRoleService;
import com.ai.web.service.WxUserService;
import com.ai.web.util.Utils;
import com.ai.web.vo.QueryData;
import com.ai.web.vo.ResultModel;
import com.ai.web.vo.WxRoleV;
import com.ai.web.vo.WxUserV;
import com.ai.web.weixin.WeixinContext;
import com.tiny.persistence.domain.WxRole;
/**
 * 微信用户管理
* @ClassName: WxUserController 
* @Description: TODO 
* @author:  
* @date: 2014年3月28日
*
 */
@Controller
@RequestMapping("/wxUser")
public class WxUserController extends BaseController {
    
    
    private static Logger logger = Logger.getLogger(WxUserController.class);
    
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private WxRoleService wxRoleService;
    
    @RequestMapping(value = "/list")
    public String list(@RequestParam(defaultValue = "") String username,
            @RequestParam(defaultValue = "") String password) {
        
        logger.info("hello......test");
        return "wxUser/wxUser_list";
    }
    
    @RequestMapping(value = "/checkRole")
    public String checkRole(@RequestParam(defaultValue = "") String username,
            @RequestParam(defaultValue = "") String password) {
        
        logger.info("hello......test");
        return "wxUser/checkRole";
    }
    
    @RequestMapping(value = "/query", produces = "application/json")
    @ResponseBody
    public QueryData query(@RequestParam HashMap<String, Object> paramMap)
            throws Exception {
        
        Map<String, Object> conditionMap = buildCondition(paramMap);
        logger.info("---- " + conditionMap);
        QueryData qd = wxUserService.queryListAndCount(conditionMap);
   	 	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<WxUserV> dataList = new ArrayList<WxUserV>();
        for(Object object:qd.getDataList()){
        	 WxUserV wxUserV = (WxUserV)object;
             if(wxUserV.getCreateTime() != null){
             	wxUserV.setCreateTimeStr(sdf.format(wxUserV.getCreateTime()));
             }
             dataList.add(wxUserV);
        }
        qd.setDataList(dataList);
        return qd;
    }
    
    @RequestMapping(value = "/new")
    public String newWxUser(Model model) {
        
        WxUserV wxUserV = new WxUserV();
        model.addAttribute("wxUserV", wxUserV);
        
        return "wxUser/wxUser_template";
    }
    
    @RequestMapping(value = "/update/{userId}")
    public String updateWxUser(@PathVariable("userId") int userId, Model model)
            throws Exception {
        
        WxUserV wxUserV = wxUserService.getWxUser(userId);
        logger.info("----- getUser:" + wxUserV);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(wxUserV.getCreateTime() != null){
        	wxUserV.setCreateTimeStr(sdf.format(wxUserV.getCreateTime()));
        }
        model.addAttribute("wxUserV", wxUserV);
        
        return "wxUser/wxUser_template";
    }
    
    //审核,也就是修改前端角色
    @RequestMapping(value = "/auditAuthUser/{userId}")
    @ResponseBody
    public ResultModel auditWxUser(@PathVariable("userId") int userId, int wxRoleId)
            throws Exception {
        WxUserV wxUserV = wxUserService.getWxUser(userId);
        WxRoleV wxRoleV = wxRoleService.getRole(wxRoleId);
        WxRole wxRole = new WxRole();
        BeanUtils.copyProperties(wxRoleV, wxRole);
        wxUserV.setWxRole(wxRole);
        wxUserV.setIsPassed(WxUserV.IS_PASSED);
        ResultModel rm = wxUserService.saveWxUser(wxUserV);  
    	logger.info("auditWxUser ResultModel:"+rm);
    	System.out.println("auditWxUser ResultModel:"+rm);
        if(rm.getStatusCode() == 20011011){
        	String serviceUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+WeixinContext.access_token;
    		String body = "{\"touser\":\""+wxUserV.getOpenId()+"\",\"msgtype\":\"text\",\"text\": {\"content\":\"您好,您的账号已经通过审核\"}}";
        	logger.info("auditWxUser url:"+serviceUrl+"  body:"+body);
        	System.out.println("auditWxUser url:"+serviceUrl+"  body:"+body);
        	try {
        		HttpResponse httpResponse = HttpUtil.httpRequest(serviceUrl, "POST", null, body);
        		logger.info("[auditWxUser] message/custom/send: " + httpResponse.toString());
        	} catch (Exception e) {
    			logger.error(e.getMessage(), e);
    		}
        }
        logger.info("----- getUser:" + wxUserV);
        return rm;
    }
    
    @RequestMapping(value = "/save", produces = "application/json")
    @ResponseBody
    public ResultModel saveWxUser(WxUserV wxUserV) throws Exception {
    	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         if(!Utils.isEmpty(wxUserV.getCreateTimeStr())){
         	wxUserV.setCreateTime(sdf.parse(wxUserV.getCreateTimeStr()));
         }
        logger.info("-----save:" + wxUserV);
        ResultModel rm = wxUserService.saveWxUser(wxUserV);
        
        return rm;
    }
    
    @RequestMapping(value = "/delete", produces = "application/json")
    @ResponseBody
    public ResultModel deleteWxUser(@RequestParam String delIds)
            throws Exception {
        
        System.out.println(delIds);
        
        List<Integer> userIds = getDeleteIds(delIds);
        ResultModel rm = wxUserService.deleteWxUsers(userIds);
        
        return rm;
    }
}
